package com.qili.service.it.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.CurrentUser;
import com.qili.entity.base.BaseDict;
import com.qili.entity.base.Col;
import com.qili.entity.base.FormType;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.supervisor.SupervisorProjectForms;
import com.qili.entity.supervisor.SupervisorProjectFormsData;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.entity.sys.SysLog;
import com.qili.mapper.search.ItFormMapper;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.SupervisorProjectFormsDataService;
import com.qili.service.supervisor.SupervisorProjectFormsService;
import com.qili.util.BeanUtil;
import com.qili.util.CommonUtil;
import com.qili.util.DateUtil;
import com.qili.util.ReType;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuyang
 * @date 2020/11/3
 * @description     科研项目具体业务类
 */
@Log
@Service("KeYanXiangMuFormService")
public class KeYanXiangMuFormServiceImpl extends FormBaseServiceImpl{

    public static final Integer FILE_COUNT = 8;

    @Autowired
    SupervisorProjectFormsService supervisorProjectFormsService;
    @Autowired
    ItFormMapper itFormMapper;
    @Autowired
    SupervisorProjectFormsDataService formsDataService;
    @Autowired
    BaseDictService baseDictService;

    @Autowired
    SysLogMapper sysLogMapper;


    public void saveFormData(SupervisorProjectFromsDTO forms, boolean ifNew) {
        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //把原来的删除:
            if(StringUtils.isBlank(forms.getSpfId())){
                throw new RuntimeException("更新表单form数据时,没有获取到form的ID");
            }
            SupervisorProjectFormsData formsData = new SupervisorProjectFormsData();
            formsData.setSpfId(forms.getSpfId());
            formsDataService.delete(formsData);
        }
        //申报项目团队成员
        SupervisorProjectFormsData spfd=new SupervisorProjectFormsData();
        spfd.setSpfId(forms.getSpfId());
        ArrayList<SupervisorProjectFormsData> formDataList1 = forms.getFormDataList();
        ArrayList<SupervisorProjectFormsData> formDataList2 = forms.getFormDataList2();
        if(CollectionUtil.isNotEmpty(formDataList1)){
            for(int i=0;i<formDataList1.size();i++){
                spfd.setSpfdataId(IdUtil.simpleUUID());
                spfd.setData1(formDataList1.get(i).getData1());
                spfd.setData2(formDataList1.get(i).getData2());
                spfd.setTableIndex(i);
                spfd.setData10("shenbaomems");
                formsDataService.insertSelective(spfd);
            }
        }
        if(CollectionUtil.isNotEmpty(formDataList2)){
            for(int i=0;i<formDataList2.size();i++){
                spfd.setSpfdataId(IdUtil.simpleUUID());
                spfd.setData1(formDataList2.get(i).getData1());
                spfd.setData2(formDataList2.get(i).getData2());
                spfd.setTableIndex(i);
                spfd.setData10("shishimems");
                formsDataService.insertSelective(spfd);
            }
        }
    }

    /**
     * 保存表单文件
     * @param forms
     * @param ifNew
     */
    public void saveFormFile(SupervisorProjectFromsDTO forms, boolean ifNew) {
        ArrayList<String> fileIds = new ArrayList<String>();
        ArrayList<String> fileIds1 = forms.getStrList2();
        ArrayList<String> fileIds2 = forms.getStrList3();
        ArrayList<String> fileIds3 = forms.getStrList4();
        ArrayList<String> fileIds4 = forms.getStrList5();
        ArrayList<String> fileIds5 = forms.getStrList6();
        ArrayList<String> fileIds6 = forms.getStrList7();
        ArrayList<String> fileIds7 = forms.getStrList8();
        ArrayList<String> fileIds8 = forms.getStrList9();
        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //编辑表单页面不需要移动文件，只是操作删除数组:
            /*ArrayList<String> strList9 = forms.getStrList9();
            if(CollectionUtil.isNotEmpty(strList9)){
                for(String delFileId:strList9){
                    //设置为回收站状态:
                    SupervisorFile delFile = new SupervisorFile();
                    delFile.setId(delFileId);
                    delFile.setDeleteState("2");
                    delFile.setDeleteUser(CommonUtil.getUserId());
                    delFile.setDeleteDate(DateUtil.getCurrentDateString());
                    dicService.updateByPrimaryKeySelective(delFile);
                }
            }*/
        }else{
            //合并:
            if(CollectionUtil.isNotEmpty(fileIds1)){
                fileIds.addAll(fileIds1);
            }
            if(CollectionUtil.isNotEmpty(fileIds2)){
                fileIds.addAll(fileIds2);
            }
            if(CollectionUtil.isNotEmpty(fileIds3)){
                fileIds.addAll(fileIds3);
            }
            if(CollectionUtil.isNotEmpty(fileIds4)){
                fileIds.addAll(fileIds4);
            }
            if(CollectionUtil.isNotEmpty(fileIds5)){
                fileIds.addAll(fileIds5);
            }
            if(CollectionUtil.isNotEmpty(fileIds6)){
                fileIds.addAll(fileIds6);
            }
            if(CollectionUtil.isNotEmpty(fileIds7)){
                fileIds.addAll(fileIds7);
            }
            if(CollectionUtil.isNotEmpty(fileIds8)){
                fileIds.addAll(fileIds8);
            }
            //这里是新建表单逻辑:
            //新建表单核心文件夹:
            String formCode = forms.getSpfF30();
            FormType formType = FormType.getFormType(formCode);
            //生成表单核心文件夹路径：（例如:/书著/2021_001_xx书著）
            //该方法执行后,会把核心文件设置为formDto的Obj1对象
            createCenterDic(forms);
            SupervisorFile centFile = (SupervisorFile) forms.getObj1();
            if(CollectionUtil.isNotEmpty(fileIds)){
                //这里面存放的是临时文件id:fileIds
                for(String shuzhuFileId : fileIds){
                    SupervisorFileTemp supervisorFileTemp = fileTempService.selectByPrimaryKey(shuzhuFileId);
                    //1.移动操作系统文件 newFile为移动后的文件
                    File newFile = moveTempFile(supervisorFileTemp, forms);
                    //2.复制数据到正式文件表
                    //更改url
                    supervisorFileTemp.setUrl(newFile.getPath());
                    SupervisorFile newSupervisorFile = new SupervisorFile();
                    BeanUtil.copyNotNullBean(supervisorFileTemp,newSupervisorFile);
                    newSupervisorFile.setZskfileType("2");
                    newSupervisorFile.setDeleteState("1");
                    //表单中的每一个文件都指向该核心文件
                    newSupervisorFile.setLinkId(centFile.getId());
                    fileService.insertFile(newSupervisorFile,(SupervisorFile) forms.getObj1());
                    //3.删除临时文件表
                    fileTempService.deleteByPrimaryKey(shuzhuFileId);
                }
            }
        }
    }

    public void insertFileLog(String filename) {
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType("DEL");
        sysLog.setText("删除文件");
        sysLog.setParam("参数:文件名称：" + filename);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser user = CommonUtil.getUser();
        sysLog.setUserName(user.getUsername());
        sysLogMapper.insert(sysLog);
    }

    /**
     * 获取表单数据
     * @param formTypeCode
     * @param formDto
     * @param model
     */
    public void getFormData(String formTypeCode, SupervisorProjectFromsDTO formDto, Model model) {
        Example famingrenExample = new Example(SupervisorProjectFormsData.class);
        famingrenExample.and().andEqualTo("data10","shenbaomems")
                .andEqualTo("spfId",formDto.getSpfId());
        famingrenExample.setOrderByClause("table_index asc");
        List<SupervisorProjectFormsData> select1 = formsDataService.selectByExample(famingrenExample);
        if(CollectionUtil.isNotEmpty(select1)){
            select1.stream().sorted(Comparator.comparing(SupervisorProjectFormsData::getTableIndex)).collect(Collectors.toList());
            if(model != null){
                model.addAttribute("team1list",JSON.toJSONString(select1));
            }else{
                formDto.setFormDataList((ArrayList)select1);
            }

        }

        Example nianfeiExample = new Example(SupervisorProjectFormsData.class);
        nianfeiExample.and().andEqualTo("data10","shishimems")
                .andEqualTo("spfId",formDto.getSpfId());
        nianfeiExample.setOrderByClause("table_index asc");
        List<SupervisorProjectFormsData> select2 = formsDataService.selectByExample(nianfeiExample);
        if(CollectionUtil.isNotEmpty(select2)){
            select2.stream().sorted(Comparator.comparing(SupervisorProjectFormsData::getTableIndex)).collect(Collectors.toList());
            if(model != null){
                model.addAttribute("team2list", JSON.toJSONString(select2));
            }else{
                formDto.setFormDataList2((ArrayList)select2);
            }
        }
    }

    /**
     * 获取科研项目统计表格数据:
     *
     * @param index 0:按计划类别统计    1:按项目级别统计    2:按项目负责人统计    3:按人员统计
     * @param formInfo
     * @return
     */
    @Override
    public ReType selectFormStatisticsTableData(String formTypeCode, SupervisorProjectFromsDTO formInfo, String index, String page, String limit) {
        if(StringUtils.isNotBlank(index)){
            if("0".equals(index) || "1".equals(index)){
                if(StringUtils.isNotBlank(formInfo.getSpfF2()) && "000".equals(formInfo.getSpfF2())){
                    formInfo.setSpfF2(null);
                }
                if(StringUtils.isNotBlank(formInfo.getSpfF3()) && "000".equals(formInfo.getSpfF3())){
                    formInfo.setSpfF3(null);
                }
            }
            if("2".equals(index) || "3".equals(index)){
                //项目负责人
                if(StringUtils.isNotBlank(formInfo.getSpfF12())){
                    formInfo.setSpfF12(formInfo.getSpfF12().trim());
                }
            }
        }
        if("0".equals(index)){
            //先根据条件,根据计划条件分组,获取计划类别名称,项目个数:
            //根据条件获取涉及的年份:
            List<String> kyxmYears0 = itFormMapper.getKyxmYears0(formInfo);
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map> projectCountList = itFormMapper.getKyxmProjectCountGroupByJhlb(formInfo);
            //获取根据符合条件的年份列表:
            if(CollectionUtil.isNotEmpty(projectCountList) && CollectionUtil.isNotEmpty(kyxmYears0)){
                for(int i=0;i<projectCountList.size();i++){
                    Map aMap = projectCountList.get(i);
                    //计划类别:
                    aMap.put("tableInd",i+1);
                    aMap.put("fileInd",i+1);
                    Object jhlb = aMap.get("jhlb");
                    if(jhlb != null){
                        String jhlbStr = (String)jhlb;

                        for(String aYear : kyxmYears0){
                            //根据条件查询某计划类别  某年的个数
                            SupervisorProjectFromsDTO dto = new SupervisorProjectFromsDTO();
                            dto.setSpfF30(formTypeCode);
                            dto.setSpfF3(jhlbStr);
                            dto.setSpfF9(formInfo.getSpfF9());
                            dto.setSpfF10(formInfo.getSpfF10());
                            dto.setFileNames1(aYear);

                            List<Map> kyxmProjectCountGroupByXmlb = itFormMapper.getKyxmProjectCountGroupByJhlb(dto);
                            if(CollectionUtil.isNotEmpty(kyxmProjectCountGroupByXmlb)){
                                aMap.put(aYear,kyxmProjectCountGroupByXmlb.get(0).get("obj2"));
                                aMap.put("theYear",aYear);
                            }else{
                                aMap.put(aYear,"0");
                                aMap.put("theYear",aYear);
                            }

                        }
                    }
                }
            }
            return new ReType(objects.getTotal(),projectCountList);
        }else if("1".equals(index)){
            //按项目级别
            //根据条件获取涉及的年份:
            List<String> kyxmYears0 = itFormMapper.getKyxmYears0(formInfo);
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map> projectCountList = itFormMapper.getKyxmProjectCountGroupByXmjb(formInfo);
            //获取根据符合条件的年份列表:
            if(CollectionUtil.isNotEmpty(projectCountList) && CollectionUtil.isNotEmpty(kyxmYears0)){
                for(int i=0;i<projectCountList.size();i++){
                    Map aMap = projectCountList.get(i);
                    //项目级别:
                    aMap.put("tableInd",i+1);
                    aMap.put("fileInd",i+1);
                    Object xmjb = aMap.get("xmjb");
                    if(xmjb != null){
                        String xmjbStr = (String)xmjb;
                        for(String aYear : kyxmYears0){
                            //根据条件查询某项目级别 某年的个数
                            SupervisorProjectFromsDTO dto = new SupervisorProjectFromsDTO();
                            dto.setSpfF30(formTypeCode);
                            dto.setSpfF2(xmjbStr);
                            dto.setSpfF9(formInfo.getSpfF9());
                            dto.setSpfF10(formInfo.getSpfF10());
                            dto.setFileNames1(aYear);
                            List<Map> kyxmProjectCountGroupByXmlb = itFormMapper.getKyxmProjectCountGroupByXmjb(dto);
                            if(CollectionUtil.isNotEmpty(kyxmProjectCountGroupByXmlb)){
                                aMap.put(aYear,kyxmProjectCountGroupByXmlb.get(0).get("obj2"));
                                aMap.put("theYear",aYear);
                            }else{
                                aMap.put(aYear,"0");
                                aMap.put("theYear",aYear);
                            }
                        }
                    }
                }
            }
            return new ReType(objects.getTotal(),projectCountList);
        }else if("2".equals(index)){
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map> kyxmProjectCountGroupByXmfzr = itFormMapper.getKyxmProjectCountGroupByXmfzr(formInfo);
            return new ReType(objects.getTotal(),kyxmProjectCountGroupByXmfzr);
        }else if("3".equals(index)){
            Map<String,Object> paraMap = new HashMap();
            if(StringUtils.isNotBlank(formInfo.getSpfF12())){
                paraMap.put("spfF12",formInfo.getSpfF12());
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF9())){
                paraMap.put("spfF9",formInfo.getSpfF9());
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF10())){
                paraMap.put("spfF10",formInfo.getSpfF10());
            }
            //查询项目级别：
            BaseDict select = new BaseDict();
            select.setBadtTypecode("XMJB001");
            List<BaseDict> select1 = baseDictService.select(select);
            if(CollectionUtil.isNotEmpty(select1)){
                paraMap.put("xmjbList",select1);
            }
            Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
            List<Map> kyxmProjectCountGroupByRy = itFormMapper.getKyxmProjectCountGroupByRy(paraMap);
            return new ReType(objects.getTotal(),kyxmProjectCountGroupByRy);
        }
        return null;
    }

    /**
     * 获取统计表格表头
     * @param formTypeCode
     * @param formInfo
     * @param index
     * @return
     */
    @Override
    public List<Col> getFormStatisticstableHead(String formTypeCode, SupervisorProjectFromsDTO formInfo, String index) {
        if(StringUtils.isBlank(index)){
            return null;
        }
        if("0".equals(index) || "1".equals(index)){
            if(StringUtils.isNotBlank(formInfo.getSpfF2()) && "000".equals(formInfo.getSpfF2())){
                formInfo.setSpfF2(null);
            }
            if(StringUtils.isNotBlank(formInfo.getSpfF3()) && "000".equals(formInfo.getSpfF3())){
                formInfo.setSpfF3(null);
            }
        }
        if("2".equals(index) || "3".equals(index)){
            //项目负责人
            if(StringUtils.isNotBlank(formInfo.getSpfF12())){
                formInfo.setSpfF12(formInfo.getSpfF12().trim());
            }
        }
        List<Col> colArrayList = new ArrayList<>();
        if("0".equals(index)) {
            //按照计划类别统计情况:
            //序号:
            colArrayList.add(new Col(null,"序号","10%","#index",null,null,false));
            //计划类别:
            colArrayList.add(new Col("obj1","计划类别","25%",null,null,null,false));
            //项目个数:
            colArrayList.add(new Col("obj2","项目个数","25%",null,null,null,false));
            //根据条件获取年份:
            List<String> kyxmYears0 = itFormMapper.getKyxmYears0(formInfo);
            if (CollectionUtil.isNotEmpty(kyxmYears0)) {
                for (String aYear : kyxmYears0) {
                    colArrayList.add(new Col(aYear,aYear + "年个数","20%",null,
                            "color: dodgerblue;cursor: pointer","showCountDetail(" + aYear + ")",false));
                }
            }
        }else if("1".equals(index)) {
            //按照项目级别统计情况:
            //按照计划类别统计情况:
            //序号:
            colArrayList.add(new Col(null,"序号","10%","#index",null,null,false));
            //计划类别:
            colArrayList.add(new Col("obj1","项目级别","25%",null,null,null,false));
            //项目个数:
            colArrayList.add(new Col("obj2","项目个数","25%",null,null,null,false));
            //根据条件获取年份:
            List<String> kyxmYears0 = itFormMapper.getKyxmYears0(formInfo);
            if (CollectionUtil.isNotEmpty(kyxmYears0)) {
                for (String aYear : kyxmYears0) {
                    colArrayList.add(new Col(aYear,aYear + "年个数","20%",null,
                            "color: dodgerblue;cursor: pointer","showCountDetail(" + aYear + ")",false));
                }
            }
        }else if("3".equals(index)){
            //按照人员统计：
            //序号:
            colArrayList.add(new Col(null,"序号","10%","#index",null,null,false));
            //姓名:
            colArrayList.add(new Col("name","姓名","10%",null,null,null,false));
            //项目个数:
            colArrayList.add(new Col("xmgs","项目个数","10%",null,null,null,false));
            //项目负责人数:
            colArrayList.add(new Col("xmfzrs","负责项目数","10%",null,null,null,false));
            //主要成员项目个数:
            colArrayList.add(new Col("zycyxmgs","主要成员项目个数\t(排名第1名至第6名)","10%",null,null,null,false));
            //其他成员项目个数:
            colArrayList.add(new Col("qtcyxmgs","其他成员项目个数\t(排名第7名及以后)","10%",null,null,null,false));
            //获取所有的项目级别
            BaseDict select = new BaseDict();
            select.setBadtTypecode("XMJB001");
            List<BaseDict> select1 = baseDictService.select(select);
            if(CollectionUtil.isNotEmpty(select1)){
                for(BaseDict baseDict : select1){
                    //某一个科研项目级别
                    colArrayList.add(new Col(baseDict.getBadtCode(),baseDict.getBadtName()+"个数","10%",null,null,null,false));
                }
            }
        }
        return colArrayList;
    }

    /**
     * 获取科研项目负责人列表
     * @return
     */
    public List<String> getXmfzrList() {
        return itFormMapper.getXmfzrList();
    }

    public ReType selectFormBook(SupervisorProjectFromsDTO formInfo, String page, String limit) {
//        Example example = new Example(SupervisorProjectForms.class);
//        example.and().andEqualTo("spfF30",formInfo.getSpfF30());
//        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
//            example.and().andLike("spfF1","%"+formInfo.getSpfF1()+"%");
//        }
//        if(StringUtils.isNotBlank(formInfo.getSpfF9())){
//            example.and().andGreaterThanOrEqualTo("spfF4",formInfo.getSpfF9());
//        }
//        if(StringUtils.isNotBlank(formInfo.getSpfF10())){
//            example.and().andLessThanOrEqualTo("spfF4",formInfo.getSpfF10());
//        }
//        if(StringUtils.isNotBlank(formInfo.getSpfF2()) && !"000".equals(formInfo.getSpfF2())){
//            example.and().andEqualTo("spfF2",formInfo.getSpfF2());
//        }
//        if(StringUtils.isNotBlank(formInfo.getSpfF3()) && !"000".equals(formInfo.getSpfF3())){
//            example.and().andEqualTo("spfF3",formInfo.getSpfF3());
//        }
//        if(StringUtils.isNotBlank(formInfo.getFileNames1())){
//            example.and().andLike("spfF4",formInfo.getFileNames1()+"%");
//        }
//        if(StringUtils.isNotBlank(formInfo.getSpfF12())){
//            example.and().andLike("spfF12","%"+formInfo.getSpfF12()+"%");
//        }
//        if(StringUtils.isNotBlank(formInfo.getSpfF7())){
//            example.and().andLike("spfF7","%"+formInfo.getSpfF7()+"%");
//        }
//        if(StringUtils.isNotBlank(formInfo.getSpfF11())){
//            example.and().andEqualTo("spfF11",formInfo.getSpfF11());
//        }
//
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andCondition("  exists (select  1  from  supervisor_file  where link_id=spf_id   and  delete_state='1')");
//        example.and(criteria);
//        example.setOrderByClause("create_date desc");
         Page<SupervisorProjectFromsDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<SupervisorProjectForms> supervisorProjectForms = itFormMapper.getkyxmtz(formInfo);
//    List<SupervisorProjectForms> supervisorProjectForms = supervisorProjectFormsService.selectByExample(example);
        if(CollectionUtil.isNotEmpty(supervisorProjectForms)){
            List<SupervisorProjectFromsDTO> formDto = getFormDto(formInfo.getSpfF30(), supervisorProjectForms);
            return new ReType(tPage.getTotal(),formDto);
        }
        return new ReType();
    }


    private List<SupervisorProjectFromsDTO> getFormDto(String formTypeCode,List<SupervisorProjectForms> supervisorProjectForms) {
        List<SupervisorProjectFromsDTO> formsDtoList = new ArrayList<SupervisorProjectFromsDTO>();
        for(int i=0;i<supervisorProjectForms.size();i++){
            SupervisorProjectForms aForm = supervisorProjectForms.get(i);
            SupervisorProjectFromsDTO aDto = changeToDto(aForm);
            getFormData(formTypeCode,aDto,null);
            setFormFiles(formTypeCode,aDto);
            aDto.setFileInd(i+1);
            formsDtoList.add(aDto);
        }
        return formsDtoList;
    }
}
